package br.com.news.activity;

import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import br.com.news.R;
import br.com.news.exception.ServiceException;
import br.com.news.service.NoticiaService;
import br.com.news.service.interfaces.INoticiaService;
import br.com.news.util.Constantes;

/**
 * Activity para a visualização de noticias
 * 
 * @author Jefferson
 * @since 07/06/2013
 */
public class NoticiaActivity extends GenericActivity{

	private INoticiaService noticiaService;
	private WebView webNoticia;
	private String textoNoticia;
	private long idNoticia;
	
	@Override
	protected int getContentView() {
		return R.layout.activity_noticia;
	}
	
	@Override
	protected void preConstruct() throws Exception {
		noticiaService = new NoticiaService(this);
	}
	
	@Override
	protected void recuperarParametros() throws Exception {
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			idNoticia = bundle.getLong(Constantes.ID_NOTICIA);
		}
		
		if (idNoticia == 0) {
			ErroActivity.chamaActivityErro(this, R.string.noticia_nao_selecionada);
			this.finish();
		}
	} 
	
	@Override
	protected void recuperaElementosDoXml() throws Exception {
		webNoticia = (WebView) findViewById(R.activity_noticia.webNoticia);
	}

	@Override
	protected void instanciaElementosDoXml() throws Exception {
		
		try {
			textoNoticia = noticiaService.buscaTextoNoticia(idNoticia);
		} catch (ServiceException e) {
			Log.e(Constantes.LOG, e.getMessage(), e);
			textoNoticia = null;
		}
		
		if (textoNoticia == null || textoNoticia.equals("NOK") ) {
			ErroActivity.chamaActivityErro(this, R.string.erro_serv_noticia);
			this.finish();
		} else {
			webNoticia.loadDataWithBaseURL(null, textoNoticia, "text/html", "utf-8", null);
		}
	}
}
